import React, { Component } from 'react';
import { Form, Input, Switch, Button, Checkbox, InputNumber, message, Radio } from 'antd';
import { connect } from 'react-redux';
import { messages } from 'share/common';
import { LanguageInput } from 'components/index';
import Chooser from 'components/chooser';
import Condition from 'components/condition';
import ExpirationDate from 'containers/supplier-management/invoice-management/invoice-management-details/component/expiration-date';
import ExpirationRadio from 'containers/supplier-management/invoice-management/invoice-management-details/component/expiration-radio';
import invoiceManagementService from '../invoice-management-service';
import 'styles/supplier-management/invoice-management/invoice-management.scss';


const FormItem = Form.Item;
const If = Condition.If;
const RadioGroup = Radio.Group;

class NewExpirationReminder extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isSaving: false,
      dataSources: [
        {
          key: 'description',
          name: messages('expense-3.key63')/*规则说明*/,
          type: 'languageInput',
          required: true,
          params: {
            inpRule: [{ length: 30, language: 'zh_cn' }, { length: 100, language: 'en' }],
            nameChange: this.handleLanguage,
            placeholder: messages('expense-3.key160')/*请填写，上限30字符*/
          }
        },
        {
          key: 'receiptTypeList',
          name: messages('common.invoice.type')/*发票类型*/,
          type: 'chooser',
          required: false,
          params: {
            type: 'select_invoice_type',
            labelKey: 'messageKey',
            valueKey: 'code',
            showNumber: false,
            placeholder:messages('common.all')/*全部*/,
            single: false
          }
        },
        {
          key: 'taxCodeList',
          name: messages('expense-3.key161')/*税收分类编码*/,
          type: 'chooser',
          required: false,
          params: {
            type: 'select_invoice_code',
            labelKey: 'name',
            valueKey: 'code',
            showNumber: false,
            placeholder:messages('common.all')/*全部*/,
            single: false
          }
        },
        {
          key: 'expiration',
          name: messages('expense-3.key162')/*校验逻辑*/,
          type: 'expiration',
          required: true,
          rules: { validator: this.handleSequenceValidator }
        },
        {
          key: 'effectiveTime',
          name: messages('expense-3.key163')/*规则生效日期*/,
          type: 'scheduled',
          required: true,
          rules: { validator: this.handleEffectiveValidator },
          params: { className: 'particular-input-width' },
          desc: messages('expense-3.key164')/*每年均按此日期计算*/
        },
        {
          key: 'expiryRemindDay',
          name: messages('expense-3.key165')/*逾期提醒设置*/,
          type: 'inputNumber',
          required: false,
          params: { min: 1, step: 1, className: 'particular-input-width', precision: 0 },
          before: messages('expense-3.key166')/*逾期前*/,
          after: messages('expense-3.key167')/*天发送提醒消息*/
        },
        {
          key: 'forceEnabled',
          name: messages('expense-3.key168')/*是否强管控*/,
          type: 'radio',
          required: false,
          desc: messages('expense-3.key169')/*配置为“是”，逾期发票不允许生成费用，已经生成费用的发票逾期，则所在报销单不允许提交*/
        }
      ],
      requestBody: { i18n: {} },
      enabled: props.params.recordExpiration && props.params.recordExpiration.id ? props.params.recordExpiration.enabled : true,
    };
  }

  componentDidMount() {
    const { params: { recordExpiration } } = this.props;
    const { form: { setFieldsValue } } = this.props;
    let requestBody = {};
    const {
      description, receiptTypeList, taxCodeList, forceEnabled, staticCalibrationFlag, expiryDay,
      expiryRemindDay, effectiveTime, dynamicRuleFailureTime
    } = recordExpiration;
    const expiration = { staticCalibrationFlag, expiryDay, dynamicRuleFailureTime };
    Object.assign(requestBody, recordExpiration);
    this.setState({ requestBody });
    setFieldsValue({
      description, receiptTypeList, taxCodeList, effectiveTime, expiration, expiryRemindDay,
      forceEnabled: forceEnabled + ''
    });
  }

  handleReg = (value, callback) => {
    let reg = /^(?:((0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-8])|(0[13-9]|1[0-2])-(29|30)|(0[13578]|1[02])-31))$/;
    if (!reg.exec(value)) {
      callback(messages('expense-3.key170')/*请选择正确的日期*/);
    }
  };

  handleEffectiveValidator = (rule, value, callback) => {
    if (value) {
      this.handleReg(value, callback);
    }
    callback();
  };

  handleSequenceValidator = (rule, value, callback) => {
    const { staticCalibrationFlag, dynamicRuleFailureTime, expiryDay } = value;
    if (!staticCalibrationFlag) {
      this.handleReg(dynamicRuleFailureTime, callback);
    }
    if (staticCalibrationFlag && !expiryDay) {
      callback(messages('common.please.input')/*请输入*/);
    }
    callback();
  };

  handleLanguage = (value, i18n) => {
    let { requestBody } = this.state;
    requestBody.i18n.description = i18n;
    this.setState({ requestBody });
  };

  handleSave = () => {
    const { form: { validateFieldsAndScroll }, params: { id } } = this.props;
    validateFieldsAndScroll((errors, values) => {
      if (!errors) {
        this.setState({ isSaving: true });
        const { requestBody  } = this.state;
        const { company: { companyOID } } = this.props;
        invoiceManagementService.submitExpirationReminder(values, requestBody, companyOID,id)
          .then(() => {
            message.success(messages('common.save.success',{arg1: ''})/*{arg1} 保存成功*/);
            this.props.close(true);
          })
          .finally(() => {
            this.setState({ isSaving: false });
          });
      } else {
        this.setState({ isSaving: false });
      }
    });
  };

  handleCancel = () => {
    const { form: { resetFields } } = this.props;
    resetFields();
    this.props.close();
  };

  renderFormItem = (item) => {
    const { requestBody, requestBody: { i18n } } = this.state;
    let funObj = {
      'input': <Input {...item.params}/>,
      'switch': <Switch {...item.params}/>,
      'chooser': <Chooser {...item.params}/>,
      'checkbox': <Checkbox {...item.params}/>,
      'scheduled': <ExpirationDate {...item.params}/>,
      'expiration': <ExpirationRadio {...item.params}/>,
      'inputNumber': <InputNumber {...item.params}/>,
      'languageInput': <LanguageInput{...item.params} name={requestBody.description} isEdit={!!requestBody.id} i18nName={(i18n || {}).description}/>,
      'radio': (
        <RadioGroup>
          <Radio value="true">{messages('common.yes')/*是*/}</Radio>
          <Radio value="false">{messages('common.no')/*否*/}</Radio>
        </RadioGroup>
      )
    };
    return funObj[item.type];
  };

  render() {
    const { dataSources, isSaving, enabled } = this.state;
    const formItemLayout = { labelCol: { span: 6 }, wrapperCol: { span: 16 } };
    const { form: { getFieldValue, getFieldDecorator } } = this.props;
    dataSources.some(item => {
      if (item.key === 'expiryRemindDay') {
        item.desc = messages('expense-3.key171',{arg1: getFieldValue(item.key)||''})/*消息内容：您的发票将于 {arg1} 天后逾期，请尽快报销*/;
        return true;
      }
    });
    return (
      <section className="new-expiration">
        <Form className="new-form" onSubmit={this.handleSave}>
          <FormItem {...formItemLayout} label={messages('common.column.status')/*状态*/}>
            {getFieldDecorator('enabled', {
              valuePropName: 'checked',
              initialValue: enabled
            })(
              <Switch onChange={enabled => this.setState({ enabled })}/>
            )}
            <span className="switch-desc">
              {enabled ? messages('common.status.enable')/*启用*/ : messages('common.status.disable')/*禁用*/}
            </span>
          </FormItem>

          {
            dataSources.map(item => {
            let rules = [{ required: item.required, message: messages('common.please.input')/*请输入*/ }];
            if (item.rules) rules.push(item.rules);
            return (
              <FormItem label={item.name}  {...formItemLayout}>
                <If value={item.before}><span
                  className="expiration-before-desc">{item.before}</span></If>
                {
                  getFieldDecorator(item.key,
                    {
                      rules: rules,
                      valuePropName: item.valuePropName || 'value'
                    }
                  )(this.renderFormItem(item))
                }
                <If value={item.after}><span>{item.after}</span></If>
                <If value={item.desc}>
                  <div className="particular-input-desc">{item.desc}</div>
                </If>
              </FormItem>
            );
          })}
          <div className="slide-footer">
            <Button type="primary" onClick={this.handleSave} loading={isSaving}>{messages('common.save')/*保存*/}</Button>
            <Button onClick={this.handleCancel}>{messages('common.cancel')/*取消*/}</Button>
          </div>
        </Form>
      </section>
    );
  }
}


function mapStateToProps(state) {
  return {
    currentMenuPermission: state.main.currentMenuPermission,
    company: state.login.company
  };
}

const WrappedComponent = Form.create()(NewExpirationReminder);
export default connect(mapStateToProps)(WrappedComponent);
